<?php
class Catalogue extends MY_Controller{
	
	function __construct()
	{
		parent::__construct();
		if(!$this->admin) redirect('admin990/login');
	}

	function index()
	{
		$cat_id = $this->uri->segment(3);
		if($cat_id == ''){
			$cat_id = 1;
		}
		$data['title'] = 'Catalogue';
		$data['menu'] = cat::find('all',array('conditions'=>array('parent_id'=>NULL)));
		$submenu = cat::find('all',array('conditions'=>'parent_id='.$cat_id));
		if($submenu){
			redirect('admin990/catalogue/'.$cat_id.'/'.$submenu[0]->id);
		}else{
		$data['submenu'] = $submenu;	
		}
		$data['product'] = product::find('all',array('conditions'=>'cat_id='.$cat_id));
		
		$data['submenu'] = $submenu;
		$this->load->view('admin/header',$data);
		$this->load->view('admin/catalogue/index');
	}
	
	function submenu()
	{
		$data['title'] = 'Catalogue';
		$parent_id = $this->uri->segment(3);
		$cat_id = $this->uri->segment(4);
		$data['menu'] = cat::find('all',array('conditions'=>array('parent_id'=>NULL)));
		$data['submenu'] = cat::find('all',array('conditions'=>'parent_id='.$parent_id));
		$data['product'] = product::find('all',array('conditions'=>'cat_id='.$cat_id));
		$this->load->view('admin/header',$data);
		$this->load->view('admin/catalogue/submenu');
	
	}
	
	function addproduct(){
		if($_POST){
			$this->form_validation->set_rules('product_name','Nom du produit','required');
			$this->form_validation->set_rules('product_num','Numéro du produit','required');
			$this->form_validation->set_rules('product_price','Prix du produit','required|numeric');
		if ($this->form_validation->run() == FALSE)
		{
			$data['msg'] = validation_errors();
		}
		else
		{
			$new_data = array('id'=>'','cat_id'=>$_POST['cat_id'],'product_num'=>$_POST['product_num'],'product_name'=>$_POST['product_name'],'product_price'=>$_POST['product_price'],'capture'=>$_POST['capture'],'status'=>1);
			
			$product = product::create($new_data);
			if($product){
				$cat = cat::find_by_id($_POST['cat_id']);
				if($cat->parent_id==NULL){
				redirect('admin990/products/'.$product->id);
				}else{
				redirect('admin990/products/'.$product->id.'?category_id='.$cat->parent_id);
				}
			}else{
				$data['msg'] = 'Il y a une erreur..';
			
			}
		}
			
		}
		
		$data['title'] = 'Catalogue';
		$this->load->view('admin/header',$data);
		$this->load->view('admin/catalogue/addproduct');
		
	}
	
	function addmenu(){
				if($_POST){
			$this->form_validation->set_rules('menu_name','Nom du menu','required');
		if ($this->form_validation->run() == FALSE)
		{
			$data['msg'] = validation_errors();
		}
		else
		{
			$new_data = array('id'=>'','cat_name'=>$_POST['menu_name'],'parent_id'=>4,'parent_name'=>'Menus');
			
			$menu = cat::create($new_data);
			if($menu){
				
				redirect('admin990/catalogue/4/'.$menu->id);
				
			}else{
				$data['msg'] = 'Il y a une erreur..';
			
			}
		}
			
		}
		
		$data['title'] = 'Catalogue';
		$this->load->view('admin/header',$data);
		$this->load->view('admin/catalogue/addmenu');
	
	}
	
}